package com.rtx.wms.std.handler.so.bak;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.so.bean.ApiOrderdetail;
import com.rtx.wms.std.so.bean.ApiOrders;
import com.rtx.wms.std.so.bean.bak.ApiOrderdetailBak;
import com.rtx.wms.std.so.bean.bak.ApiOrdersBak;
import com.rtx.wms.std.so.service.ApiOrdersBakService;
import com.rtx.wms.std.so.service.ApiOrdersService;

@Service
public class ApiOrderBakHandle {
	
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	ApiOrdersService apiOrdersService;
	
	@Autowired
	ApiOrdersBakService apiOrdersBakService;
	
	
	public void handleBak(String whseid) {
		//获取待备份数据
		List<ApiOrders> list = queryBakList(whseid);
		for(ApiOrders o:list) {
			try {
				//获取待备份数据
				mappingAndInsertBak(whseid,o);
				//删除数据
				apiOrdersService.deleteApiOrders(whseid, o);
			} catch (Exception e) {
				logger.error("备份异常-",e);
			}
			
		}
		
	}
	
	//获取待备份数据
	private List<ApiOrders> queryBakList(String whseid) {
		LambdaQueryWrapper<ApiOrders> qw = Wrappers.lambdaQuery();
		qw.eq(ApiOrders::getEdiflag, WmsConstant.SUCCESS_FLAG);
		qw.lt(ApiOrders::getAdddate, LocalDateTime.now().plusDays(-10));
		qw.last("limit 500");
		return apiOrdersService.selectApiOrdersByWrapper(whseid, qw,null);
	}
	
	
	//写入备份表
	private void mappingAndInsertBak(String whseid,ApiOrders o) throws Exception {
		
		ApiOrdersBak bak = new ApiOrdersBak();
		BeanUtils.copyProperties(bak, o);
		List<ApiOrderdetailBak> dList = new ArrayList<ApiOrderdetailBak>();
		for(ApiOrderdetail detail:o.getDetails()) {
			ApiOrderdetailBak dBak = new ApiOrderdetailBak();
			BeanUtils.copyProperties(dBak, detail);
			dList.add(dBak);
		}
		bak.setDetails(dList);
		
		
		apiOrdersBakService.addApiOrders(whseid, bak);
	}
}
